/*
 * @Descripttion:
 * @Author: Zhai Penghui
 * @Date: 2021-11-05 10:04:35
 */

import { login } from "../../api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
const state = {
  token: getToken(),
};
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
};
const actions = {
  login({ commit }, data) {
    const { username, password } = data;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          const { data } = response;
          console.log(data);
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          resolve({ code: 0 });
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // user logout
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      
        try {
          commit("SET_TOKEN", "");

          removeToken();
          //   resetRouter();

          resolve();
        } catch (error) {
          reject(error);
        }
      
    });
  },
};

export default {
  namespaced: true, // 命名空间,用于在全局引用此文件里的方法时标识这一个的文件名。解决命名冲突问题
  state,
  mutations,
  actions,
};
